<!DOCTYPE html>
<html lang="zh-Hans-CN">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>文字溢出hover滚动</title>
  <style>
    * {
      box-sizing: border-box;
      font-size: 30px;
    }

    .parent {
      white-space: nowrap;
      width: 300px;
      overflow: hidden;
      border: 1px solid saddlebrown;
      display: flex;
      --text-gap: 30px
    }

    .parent span {
      display: inline-block;
    }

    .animate span {
      animation: var(--words-roll-time, 5s) wordsRoll linear;
    }

    @keyframes wordsRoll {
      from {
        transform: translateX(0%);
      }

      to {
        transform: translateX(calc(-100% - var(--text-gap)));
      }
    }
  </style>
</head>

<body>


  <div class="parent">
    <span>床前明月光，疑是地上霜。 举头望明月，低头思故乡。</span>
  </div>



  <script>
    function useTextScroll(selector) {

      const el = document.querySelector(selector)
      const speed = 150
      if (el.clientWidth > el.firstElementChild.scrollWidth) {
        return;
      }

      const cloneNode = el.firstElementChild.cloneNode(true)
      el.style.setProperty('--words-roll-time', el.firstElementChild.scrollWidth / speed + 's')
      el.addEventListener('mouseenter', () => {
        el.classList.add('animate')
        cloneNode.addEventListener('animationend', () => {
          el.classList.remove('animate')
        }, { once: true })
      })

      cloneNode.style.marginLeft = 'var(--text-gap)'
      el.appendChild(cloneNode)
    }
    useTextScroll('.parent')
  </script>
</body>

</html>